function initTooltips() {
    $(document).tooltip({
        items: "[data-title]",
        track: true,
        content: function () {
            return $(this).data('title');
        }
    });
}

function initForms() {
	jQuery(document).on("relaod:saveGame", function() {
		ajaxGameSaveShow();
	});
	jQuery(document).on("relaod:gamesTable", function() {
		ajaxGamesTableShow();
	});
	jQuery(document).on("relaod:gamesKWSummaryTable", function() {
		ajaxGamesKWSummaryShow();
	});
	jQuery(document).on("relaod:randomGameTable", function() {
		ajaxRandomGameShow();
	});
	
	initInputs();
	
}

function initInputs() {
	jQuery(document).on('click','input[type=checkbox]',function() {
		jQuery(document).trigger("relaod:saveGame");
		}
	);
	jQuery(document).on('click','input[name=saveGame]',ajaxGameSave);
	jQuery(document).on('click','input[name=saveGameScoreBoard]',ajaxGameSaveScoreBoard);
	jQuery(document).on('click','input[name=startgame]',ajaxDartautomat);
	jQuery(document).on('click','#randomGameTabel',function() {
		jQuery(document).trigger("relaod:randomGameTable");
		}
	);
	jQuery("#gameSelect").on("change", function() {
		ajaxRandomGameShowByGameID(this.value);
	});
}

function ajaxGameSaveScoreBoard(event) {
	event.preventDefault();
	var url = "ajax.php?request=gameSave&";
	$.ajax({
	  url: url + jQuery('#playersForm').serialize(),
	  encoding:"UTF-8",
	  context: document.body
	}).done(function(data) {
		jQuery('input[name=saveGameScoreBoard]').remove();
		window.close();
	});
}

function ajaxGameSave(event) {
	event.preventDefault();
	var url = "ajax.php?request=gameSave&";
	$.ajax({
	  url: url + jQuery('#playersForm').serialize(),
	  encoding:"UTF-8",
	  context: document.body
	}).done(function(data) {
		$('#gameSaveContainer').html( data );
		jQuery(document).trigger("relaod:gamesTable");
		jQuery(document).trigger("relaod:gamesKWSummaryTable");
		jQuery(document).trigger("relaod:randomGameTable");
		initHover();
	});
}

function ajaxGameSaveShow() {
	var url = "ajax.php?request=gameSaveShow&";
	$.ajax({
	  url: url + jQuery('#playersForm').serialize(),
	  encoding:"UTF-8",
	  context: document.body
	}).done(function(data) {
		$('#gameSaveContainer').html( data );
		jQuery('input[type=checkbox]').bind('click',function() {
			jQuery(document).trigger("relaod:saveGame");
			}
		);
		jQuery('input[name=saveGame]').bind('click',ajaxGameSave);
		jQuery("#gameSelect").on("change", function() {
			ajaxRandomGameShowByGameID(this.value);
		});
		initHover();
		initTreeView();
	});
}

function ajaxGamesTableShow() {
	var url = "ajax.php?request=gamesTableShow&";
	$.ajax({
	  url: url + jQuery('#playersForm').serialize(),
	  encoding:"UTF-8",
	  context: document.body
	}).done(function(data) {
		$('#gamesTable').html( data );
		jQuery('input[type=checkbox]').bind('click',function() {
			jQuery(document).trigger("relaod:saveGame");
			}
		);
		jQuery('input[name=saveGame]').bind('click',ajaxGameSave);
		jQuery("#gameSelect").on("change", function() {
			ajaxRandomGameShowByGameID(this.value);
		});
		initHover();
	});
}

function ajaxGamesKWSummaryShow() {
	var url = "ajax.php?request=gamesKWSummaryShow&";
	$.ajax({
	  url: url + jQuery('#playersForm').serialize(),
	  encoding:"UTF-8",
	  context: document.body
	}).done(function(data) {
		$('#gamesKWSummary').html( data );
	});
}

function ajaxRandomGameShowByGameID(gameID) {
	var url = "ajax.php?request=randomGameShowByGameID&";
	$.ajax({
	  url: url + jQuery('#playersForm').serialize(),
	  encoding:"UTF-8",
	  gameID:gameID,
	  context: document.body
	}).done(function(data) {
		$('#randomGameTabel').html( data );
	});
}

function ajaxRandomGameShow() {
	var url = "ajax.php?request=randomGameShow&";
	$.ajax({
	  url: url + jQuery('#playersForm').serialize(),
	  encoding:"UTF-8",
	  context: document.body
	}).done(function(data) {
		$('#randomGameTabel').html( data );
	});
}

function ajaxDartautomat(event) {
	event.preventDefault();
	var url = "dartautomat.php?request=startdartboard&";
	var params = jQuery('#playersForm').serialize();
	url = url + params;

	jQuery.initWindowMsg();
	var dartboardWin = window.open(url,'dartboardWin', "width=770, height=890, location=no, menubar=no, scrollbars=no, status=no, toolbar=no");
    if (window.focus) {
		dartboardWin.focus();
	}

	return false;
}

function initContextMenu(type,title){
	if (type == "deleteGame") {
		var items = {
			"delete": {name: "Spiel l&ouml;schen", icon: "deletegame"}
		}
	} else if (type == 'statisticByPlayer') {
		var items = {
			"statistic": {name: title, icon: "statistic"},
			"topGames": {name: "Top Spiele", icon: "statistic"},
			"sep1": "---------",
			"statisticWeeks": {name: "Wochenverlauf (Line)", icon: "statistic"},
			"sep2": "---------",
			"statisticWeeksPlayer": {name: "Wochenverlauf (Candelstick)", icon: "statistic"},
			"statisticHitsPlayer": {name: "Top Segmente (Balken)", icon: "statistic"},
			"statisticHitsPlayerPie": {name: "Top Segmente (Pie)", icon: "statistic"}
		}
	} else if (type == 'statisticByGame') {
		var items = {
			"statistic": {name: title, icon: "statistic"},
			"gamedetails": {name: "Spiel-Details", icon: "statistic"},
			"gamedetails2": {name: "Spiel-Endstand", icon: "statistic"}
		}
	} else {
		var items = {
			"statistic": {name: title, icon: "statistic"}
		}
	}
    jQuery.contextMenu({
        selector: '.'+type, 
        callback: function(key, options) {
            var m = "clicked: " + key;
			var playerID = jQuery(options.$trigger.context).data('player-id');
			var gameID = jQuery(options.$trigger.context).data('game-id');
			var gameUUID = jQuery(options.$trigger.context).data('game-uuid');
			var id = jQuery(options.$trigger.context).data('id');
			if (key == 'statistic') {
				event.preventDefault();
				var url = "ajax_statistics.php?request="+type+"&playerID="+playerID+"&gameID="+gameID+"&gameUUID="+gameUUID;
				
				jQuery.ajax({
					type:       "POST",
					url:        url,
					dataType:   'html',
					success:    function(data){
						jQuery("#statisticsDialog").html(data);
						jQuery("#statisticsDialog").dialog({  //create dialog, but keep it closed
							height: '800',
							width: 'auto',
							modal: true,
							title: title
						});
					}
				});
			} else if (key == 'delete') {
				event.preventDefault();
				var url = "ajax.php?request="+type+"&id="+id;
				
				jQuery.ajax({
					type:       "POST",
					url:        url,
					dataType:   'html',
					success:    function(data){
						$('#gamesTable').html( data );
					}
				});
			} else if (key == 'topGames') {
				event.preventDefault();
				jQuery('body').append("<div id='statisticsDialog"+playerID+"'></div>");
				var url = "ajax_statistics.php?request="+key+"&playerID="+playerID;
				jQuery.ajax({
					type:       "POST",
					url:        url,
					dataType:   'html',
					success:    function(data){
						jQuery("#statisticsDialog"+playerID).html(data);
						jQuery("#statisticsDialog"+playerID).dialog({  //create dialog, but keep it closed
							height: 'auto',
							width: 'auto',
							modal: false,
							title: 'Top Spiele'
						});
					}
				});
			} else if (key == 'gamedetails') {
				event.preventDefault();
				var url = "ajax_statistics.php?request="+key+"&gameUUID="+gameUUID;
				
				jQuery.ajax({
					type:       "POST",
					url:        url,
					dataType:   'html',
					success:    function(data){
						jQuery("#statisticsDialog").html(data);
						jQuery("#statisticsDialog").dialog({  //create dialog, but keep it closed
							height: '800',
							width: 'auto',
							modal: true,
							title: title
						});
					}
				});
			} else if (key == 'gamedetails2') {
				event.preventDefault();
				var url = "dartautomat.php?request="+key+"&gameUUID="+gameUUID;
				
				jQuery.ajax({
					type:       "POST",
					url:        url,
					dataType:   'html',
					success:    function(data){
						dartScoreBoardWin = window.open(url,"Scoreboard", "width=1300, height=800, location=no, menubar=no, scrollbars=no, status=no, toolbar=no");
						if (window.focus) {
							dartScoreBoardWin.focus();
						}
					}
				});
			} else if (key == 'statisticWeeks') {
				event.preventDefault();
				var url = "ajax_statistics.php?request="+key;
				
				jQuery.ajax({
					type:       "POST",
					url: 		url + "&" + jQuery('#playersForm').serialize(),
					dataType:   'html',
					success:    function(data){
						jQuery("#statisticsDialog").html(data);
						jQuery("#statisticsDialog").dialog({  //create dialog, but keep it closed
							height: 'auto',
							width: '800',
							modal: false,
							title: 'Wochenstatistik',
							resizable: false,
						});
						plot1.replot( { resetAxes: true } );
					}
				});
			} else if (key == 'statisticWeeksPlayer') {
				event.preventDefault();
				jQuery('body').append("<div id='statisticsDialog"+playerID+"'></div>");
				var url = "ajax_statistics.php?request="+key+"&playerID="+playerID;
				jQuery.ajax({
					type:       "POST",
					url: 		url,
					dataType:   'html',
					success:    function(data){
						var resultObj = eval (data);
						plot1 = $.jqplot('statisticsDialog'+playerID,[resultObj],{
						  seriesDefaults:{yaxis:'y2axis'},
						  axes: {
							  xaxis: {
								renderer: $.jqplot.DateAxisRenderer,
								tickOptions: { formatString: '%d.%m.%y' }
							},
							y2axis: {
								min:0,
								max:1,
								ticks:[0, 0.25, 0.5, 0.75, 1],
								tickOptions:{ prefix: '' }
							}
						  },
						  series: [{renderer:$.jqplot.OHLCRenderer, 
									rendererOptions:{	candleStick:true,
														upBodyColor:'#33CC00',fillUpBody:true,
														downBodyColor:'#FF0000',fillDownBody:true}}
						  ],
						  cursor:{ 
							show: true,
							zoom:true, 
							showTooltip:true
						 } 
						});
						
						jQuery("#statisticsDialog"+playerID).html(data);
						jQuery("#statisticsDialog"+playerID).dialog({  //create dialog, but keep it closed
							height: '400',
							width: '800',
							modal: false,
							title: 'Wochenstatistik Spieler '+playerID,
							resizable: false,
						});
						plot1.replot( { resetAxes: true } );
					}
				});
			} else if (key == 'statisticHitsPlayer') {
				event.preventDefault();
				jQuery('body').append("<div id='statisticsDialog"+playerID+"'></div>");
				var url = "ajax_statistics.php?request="+key+"&playerID="+playerID;
				jQuery.ajax({
					type:       "POST",
					url: 		url,
					dataType:   'html',
					success:    function(data){
						var resultObj = eval (data);
						var ticks = resultObj[0];
				 
						plot1 = $.jqplot('statisticsDialog'+playerID, [resultObj[1]], {
							seriesDefaults:{
								renderer:$.jqplot.BarRenderer,
								rendererOptions: { barWidth: '50' },
								pointLabels: { show: true }
							},
							axes: {
								xaxis: {
									renderer: $.jqplot.CategoryAxisRenderer,
									ticks: ticks
								},
								yaxis: {
									renderer: $.jqplot.CategoryTickRenderer,
									min:0,
									max:parseInt(resultObj[1][0])+parseInt(resultObj[1][0])/5
							    },
							}
						});
						
						jQuery("#statisticsDialog"+playerID).html(data);
						jQuery("#statisticsDialog"+playerID).dialog({  //create dialog, but keep it closed
							height: '400',
							width: '800',
							modal: false,
							title: 'Statistik Hits Player '+playerID,
							resizable: false,
						});
						plot1.replot( );
					}
				});
			} else if (key == 'statisticHitsPlayerPie') {
				event.preventDefault();
				jQuery('body').append("<div id='statisticsDialog"+playerID+"'></div>");
				var url = "ajax_statistics.php?request="+key+"&playerID="+playerID;
				jQuery.ajax({
					type:       "POST",
					url: 		url,
					dataType:   'html',
					success:    function(data){
						var resultObj = eval (data);
				 
						var plot1 = jQuery.jqplot ("statisticsDialog"+playerID, [resultObj], 
						{ 
							seriesDefaults: {
								// Make this a pie chart.
								renderer: jQuery.jqplot.PieRenderer, 
								rendererOptions: {
								  // Put data labels on the pie slices.
								  // By default, labels show the percentage of the slice.
								  showDataLabels: true
								}	
							}, 
							legend: { show:true, location: 'e', placement:'insideGrid'}
						});
						
						jQuery("#statisticsDialog"+playerID).html(data);
						jQuery("#statisticsDialog"+playerID).dialog({  //create dialog, but keep it closed
							height: '400',
							width: '400',
							modal: false,
							title: 'Statistik Hits Player '+playerID,
							resizable: false,
						});
						plot1.replot( );
					}
				});
			}
        },
		items : items
    });
    
    /*jQuery('.context-menu-one').on('click', function(e){
        console.log('clicked', this);
    })*/
};

function initHover(){
	$(".resizeover").hoverIntent(function() {
		var $this = $(this);
		$this.css("overflow","overlay");
		$this.animate({
			'height': 305
		});
	},function() {
		var $this = $(this);
		$this.animate({
			'height': 165
		}, 200, function() {
			$this.css("overflow","hidden");
		});
	});
	$(".scrollbarover").hoverIntent(function() {
		var $this = $(this);
		$this.css("overflow","overlay");
	},function() {
		var $this = $(this);
		$this.css("overflow","hidden");
	});
	var timer = setInterval(function() {
		var url = "ajax.php?request=livelink";
		$('#livelink').load(url);
	}, 30000); 
};

function initTreeView() {
	$(function () { 
		$('#gameselecttree').jstree();
		$('#gameselecttree').css('display','block');
	});
	$('#gameselecttree').on('changed.jstree', function (e, data) {
		var gameID = data.instance.get_node(data.selected).data.gameId;
		var gameIDNew = data.instance.get_node(data.selected).data.gameIdNew;
		$("#gameSelect").val(gameID);
		if(gameIDNew != 0) {
			$("#startgame").removeAttr('disabled');  
			$('#startgame').css('color','green');	
			$('#startgame').css('font-weight','bold');			
		} else {
			$("#startgame").attr('disabled', 'disabled');
			$('#startgame').css('color','red');			
		}
		ajaxRandomGameShowByGameID(gameID);
	});
};

function initNewsSlider() {
	$('.iosSlider').iosSlider({
		desktopClickDrag: true,
		snapToChildren: true,
		autoSlide: true,
		infiniteSlider: true
	});
	
	$('.iosSlider').hoverIntent(function() {
		var $this = $('.statisticLayer');
		$this.fadeToggle( "fast", "swing" );
		plot1.replot( );
		plot2.replot( );
	},function() {
		var $this = $('.statisticLayer');
		$this.fadeToggle( "fast", "swing" );
	});
	
	jQuery.ajax({
		type:       "POST",
		url: 		"ajax_statistics.php?request=dartsPerWeek",
		dataType:   'html',
		success:    function(data){
			plot1 = $.jqplot ('chartOverlay1', eval(data),
			{
				title: 'Darts pro Woche'/*,
				seriesDefaults: { 
					showMarker:false,
					pointLabels: { show:true } 
				}*/
			});
		}
	});
	jQuery.ajax({
		type:       "POST",
		url: 		"ajax_statistics.php?request=statisticHitsAll",
		dataType:   'html',
		success:    function(data){
			var resultObj = eval (data);
			var ticks = resultObj[0];
	 
			plot2 = $.jqplot('chartOverlay2', [resultObj[1]], {
				title: 'Top Segmente',
				seriesDefaults:{
					renderer:$.jqplot.BarRenderer,
					rendererOptions: { barWidth: '20' },
					pointLabels: { show: true }
				},
				axes: {
					xaxis: {
						renderer: $.jqplot.CategoryAxisRenderer,
						ticks: ticks
					},
					yaxis: {
						renderer: $.jqplot.CategoryTickRenderer,
						min:0,
						max:parseInt(resultObj[1][0])+parseInt(resultObj[1][0])/5,
						tickOptions: {
						  showGridline: false,
						  showMark: false,
						  showLabel: false,
						  shadow: false,
						},
					},
				}
			});
		}
	});
};

var plot1;
var plot2;

jQuery(document).ready(function() {
	initForms();
	initContextMenu('statisticByPlayer','Alle Spiele des Spieler');
	initContextMenu('statisticByGame','Alle Spiele der Spielgruppe');
	initContextMenu('statisticByGameAndPlayer','Alle Spiele des Spieler der Spielgruppe');
	initContextMenu('deleteGame','Spiel löschen');
	initTooltips();
	initHover();
	initTreeView();
	initNewsSlider();
});